# coding:utf-8

import subprocess
import shlex
import os
import sys


def execute_liquibase(root_dir=None):
    """
    设置Liquibase命令和参数，执行脚本

    :param root_dir: 起始目录
    :return: 执行结果
    """

    if not root_dir:
        print("没有传入脚本目录")
        raise ValueError("必须输入目录")

    # liquibase 执行文件绝对路径
    liquibase_command = "liquibase"
    driver = "com.mysql.cj.jdbc.Driver"
    # 数据库地址jdbc:your_database_url
    url_bas = "jdbc:mysql://116.63.83.234:36001/"
    user = "erp_user"
    password = "hkabc_123"
    # url_bas = "jdbc:mysql://ct-polardb-test.mysql.polardb.rds.aliyuncs.com:3306/"
    # user = "test_user"
    # password = "test_@*202"

    # 遍历目录
    for dirpath, dirnames, filenames in os.walk(root_dir):
        # 找到包含changlog文件夹的这一层，就是总的xml所处的文件夹，在这里执行liqiubase命令即可
        # print("dirnames:", dirnames)
        if dirnames == ['changelog']:
            if dirpath[-1] == "/":
                data_base = dirpath.split("/")[-2]
            else:
                data_base = dirpath.split("/")[-1]
            # print("data_base:", data_base)
            if data_base in filenames[0]:
                # xml_file = os.path.join(dirpath, filenames[0])
                xml_file = filenames[0]
                # 构建完整的命令参数
                url = url_bas + data_base + "?useCompression=true"
                args = [
                    liquibase_command ,
                    "--driver", driver,
                    "--changeLogFile", shlex.quote(xml_file),
                    "--url", url,
                    "--username", user,
                    "--password", password,
                    "--logLevel", "SEVERE update"  # 设置日志级别，根据需要调整
                ]

                liqubas_args = ' '.join(args)
                process  = subprocess.run(liqubas_args, cwd=dirpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
                # 打印标准输出和标准错误
                # print('stdout:', process.stdout.strip())
                # print('stderr:', process.stderr.strip())
                # 检查返回码以确定命令是否成功执行
                if process.returncode == 0:
                    print("+++++++++++++++")
                    # print(liqubas_args)
                    print(data_base, "升级成功")
                    print("+++++++++++++++")
                else:
                    print("!!!!!!!!!!!!!!!")
                    print(data_base, "升级失败")
                    print("升级命令：", liqubas_args)
                    print(f"命令执行失败，返回码：{process.returncode}")
                    print("错误信息：")
                    print(process.stderr.strip())  # 打印错误输出
                    print("")

        else:
            pass
            # print("未找到 changelog 目录，当前为：", dirpath, dirnames)

if __name__ == '__main__':
    change_log_dir = sys.argv[1]
    # change_log_dir =  r"E:\H.恒康信息科技\B.版本相关\F.升级记录\Z.中台相关\J.二代脚本\V2.48\表结构\V2.48\20240417140655"
    if os.path.exists(change_log_dir):
        execute_liquibase(change_log_dir)
